package webview

import (
	"gitee.com/snxamdf/wui/logs"
	"gitee.com/snxamdf/wui/util"
)

type SockJSSyncHandler struct {
}

//小控件数据更新监听
func (SockJSSyncHandler) BindWidgetUpdateListen(wd RPCData) {
	widgetLock.Lock()
	defer widgetLock.Unlock()
	//logs.Info("listen-data:", ToJson(wd))
	//for bindKey, _ := range wd {
	//	data := wd.GetMap(bindKey)
	//	if data != nil {
	//		//logs.Info("",data)
	//		widgetsId := data.GetMap("widgetsId")
	//		var valueType = data.Type("value")
	//		if valueType == "map" {
	//			//数据结构是 map
	//			//newValue := data.GetMap("value")
	//			//logs.Info("map==:", "widgetsId:", widgetsId, " newValue:", newValue)
	//		} else if valueType == "array" {
	//			//数据结构是 []map
	//			//newValue := data.GetArrayMap("value")
	//			//logs.Info("array==:", "widgetsId:", widgetsId, "newValue:", newValue)
	//		} else if valueType == "string" {
	//			//数据结构是 string
	//			newValue := data.GetString("value")
	//			//logs.Info("string==:", "widgetsId:", widgetsId, "[", widgetsIdType, "]", "newValue:", newValue)
	//			//更新
	//			for widgetId, _ := range widgetsId {
	//				//logs.Info("widgetId==:", widgetId)
	//				if widget, ok := widgetListen[widgetId]; ok {
	//					widget.SetValue(newValue)
	//				}
	//			}
	//		} else if valueType == "int" {
	//
	//		}
	//	}
	//}
}

//小控件事件绑定 click 事件
func (SockJSSyncHandler) BindWidgetClickEventListen(wd RPCData, fn Callback) {
	widgetLock.Lock()
	defer widgetLock.Unlock()
	widgetId := wd.WidgetId
	var tmpWidgetId = widgetId
	if tmpWidgetId[:1] == "#" {
		tmpWidgetId = tmpWidgetId[1:]
	}
	logs.Debug("eventBindWidgetListenClick", tmpWidgetId)
	if widget, ok := widgetListen[tmpWidgetId]; ok {
		var r interface{}
		e := widget.GetEvent()
		if e != nil {
			r = e(widget)
		}
		args, err := util.EventResult("0", "click", widgetId, r)
		if err != nil {
			logs.Error("事件返回结果包装错误：", err)
		} else {
			fn(args)
		}
	} else {
		args, err := util.EventResult("-1", "click", widgetId, nil)
		if err != nil {
			logs.Error("事件返回结果包装错误：", err)
		} else {
			fn(args)
		}
	}
}

//小控件事件绑定 change 事件
func (SockJSSyncHandler) BindWidgetChangeEventListen(wd RPCData, fn Callback) {
	widgetLock.Lock()
	defer widgetLock.Unlock()
	widgetId := wd.WidgetId
	var tmpWidgetId = widgetId
	if tmpWidgetId[:1] == "#" {
		tmpWidgetId = tmpWidgetId[1:]
	}
	logs.Debug("eventBindWidgetListenChange", tmpWidgetId)
	if widget, ok := widgetListen[tmpWidgetId]; ok {
		var r interface{}
		e := widget.GetEvent()
		if e != nil {
			r = e(widget)
		}
		args, err := util.EventResult("0", "click", widgetId, r)
		if err != nil {
			logs.Error("事件返回结果包装错误：", err)
		} else {
			fn(args)
		}
	} else {
		args, err := util.EventResult("-1", "click", widgetId, nil)
		if err != nil {
			logs.Error("事件返回结果包装错误：", err)
		} else {
			fn(args)
		}
	}
}

func (m SockJSSyncHandler) Listen(wd RPCData) {

}
